//
//  PhotoAssetPreviewViewController.m
//  XPhoto
//
//  Created by baboy on 2020/6/22.
//  Copyright © 2020 baboy. All rights reserved.
//

#import "PhotoAssetPreviewViewController.h"
#import <AFNetworking/UIImageView+AFNetworking.h>
#import "PHAsset+x.h"

@interface PhotoAssetPreviewViewController ()

@end

@implementation PhotoAssetPreviewViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
}

- (PhotoPreviewView *)createPlayerWithPhotoAsset:(PhotoAsset *)photoAsset{
    PhotoPreviewView *view = [[PhotoPreviewView alloc] initWithFrame:self.contentView.bounds withMediaType:photoAsset.type];
    view.autoresizingMask = UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight;

    if (photoAsset.asset) {
        [photoAsset.asset videoURLAssetWithProgressHandler:^(double progress, NSError * _Nonnull error) {
            dispatch_async(dispatch_get_main_queue(), ^{
                view.loadProgress = progress;
            });
        }
                                             resultHandler:^(AVURLAsset * _Nonnull urlAsset, NSError * _Nonnull error) {
            dispatch_async(dispatch_get_main_queue(), ^{
                view.playerView.videoURLAsset = urlAsset;
            });
        }];
    }
    NSBlockOperation *operation = [NSBlockOperation blockOperationWithBlock:^{
        if (photoAsset.originImage) {
            dispatch_async(dispatch_get_main_queue(), ^{
                view.playerView.coverImage = photoAsset.originImage;
            });
            return;
        }
        if (photoAsset.originPath) {
            view.playerView.coverURL = [NSURL fileURLWithPath:photoAsset.originPath];
            return;
        }
        if (photoAsset.asset) {
            [photoAsset.asset loadHighQualityImageWithProgressHandler:^(double progress, NSError * _Nonnull error) {
                dispatch_async(dispatch_get_main_queue(), ^{
                });
                
            }
                                                                   resultHandler:^(UIImage * _Nonnull result, NSDictionary * _Nonnull info) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    view.playerView.coverImage = result;
                    photoAsset.originImage = result;
                });
            }];
            return;
        }
    }];
    [self.photoLoadQueue addOperation:operation];
    return view;
}

- (PhotoPreviewView *)createImageViewWithPhotoAsset:(PhotoAsset *)photoAsset{
    PhotoPreviewView *view = [[PhotoPreviewView alloc] initWithFrame:self.contentView.bounds withMediaType:photoAsset.type];
    view.autoresizingMask = UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight;

    NSBlockOperation *operation = [NSBlockOperation blockOperationWithBlock:^{

        if (photoAsset.originImage) {
            view.imageView.image = photoAsset.originImage;
            return;
        }
        if (photoAsset.originPath) {
            dispatch_async(dispatch_get_main_queue(), ^{
                [view.imageView setImageWithURL:[NSURL fileURLWithPath:photoAsset.originPath]];
            });
            return;
        }
        if (photoAsset.asset) {
            [photoAsset.asset loadHighQualityImageWithProgressHandler:^(double progress, NSError * _Nonnull error) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    DLOG(@"%@,%f", photoAsset.asset.localIdentifier, progress);
                    view.loadProgress = progress;
                    
                });
                
            }
                                                                   resultHandler:^(UIImage * _Nonnull result, NSDictionary * _Nonnull info) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    view.imageView.image = result;
                });
            }];
            return;
        }
    }];
    [self.photoLoadQueue addOperation:operation];
    return view;
}


- (PhotoPreviewView *)createItemViewWithPhotoAsset:(PhotoAsset *)photoAsset{
    PhotoPreviewView *itemView = nil;
    if (photoAsset.type == PhotoAssetTypePhoto) {
        itemView = [self createImageViewWithPhotoAsset:photoAsset];
    }
    if (photoAsset.type == PhotoAssetTypeVideo) {
        itemView = [self createPlayerWithPhotoAsset:photoAsset];
    }
    return itemView;
}
- (PhotoPreviewView *)createItemViewWithAsset:(PHAsset *)asset{
    PhotoPreviewView *itemView = nil;
    PhotoAsset *photoAsset = [PhotoAsset new];
    photoAsset.asset = asset;
    if (asset.mediaType == PHAssetMediaTypeImage) {
        photoAsset.type = PhotoAssetTypePhoto;
        itemView = [self createImageViewWithPhotoAsset:photoAsset];
    }
    if (asset.mediaType == PHAssetMediaTypeVideo) {
        photoAsset.type = PhotoAssetTypeVideo;
        itemView = [self createPlayerWithPhotoAsset:photoAsset];
    }
    return itemView;
}
@end

@implementation PhotoPreviewView
- (id)initWithFrame:(CGRect)frame withMediaType:(NSInteger)mediaType{
    if (self = [super initWithFrame:frame]) {
        self.mediaType = mediaType;
        if (mediaType == PhotoAssetTypePhoto) {
            _imageView = [[UIImageView alloc] initWithFrame:self.bounds];
            _imageView.contentMode = UIViewContentModeScaleAspectFit;
            _imageView.autoresizingMask = UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight;
            _imageView.clipsToBounds = YES;
            [self addSubview:_imageView];
        }
        if (mediaType == PhotoAssetTypeVideo) {
            _playerView = [BKPlayerView view];
            _playerView.shouldAutoPlay = NO;
            _playerView.showControls = YES;
            _playerView.playMode = BKPlayerPlayModeSingleLoop;
            _playerView.autoresizingMask = UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight;
            _playerView.frame = self.bounds;
            [self addSubview:_playerView];
        }
        self.layer.borderColor = [UIColor greenColor].CGColor;
        self.layer.borderWidth = 5.0f;
        
        CGRect progressViewFrame = CGRectMake(self.bounds.size.width - 30, self.bounds.size.height - 30, 20, 20);
        _progressView = [[CircleProgressBar alloc] initWithFrame:progressViewFrame];
        _progressView.solid = YES;
        _progressView.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleTopMargin;
        _progressView.hidden = YES;
        [self addSubview:_progressView];
    }
    return self;
}
- (void)setLoadProgress:(double)loadProgress{
    self.progressView.hidden = loadProgress == 1;
    self.progressView.progress = loadProgress;
}
@end
